﻿using System;
using System.Net.Sockets;
using System.Net;
using MessageSystem.Default.Interface;
using MessageSystem.Managed.Interface;

namespace MessageSystem.Default.implement
{
    class Acceptor 
    {
        public Acceptor(IMessageChannelFactory factory, Selector selector,OnAccept oa)
        {
            m_pFactory = factory;
            m_pSelector = selector;
            m_OnAccept = oa;
        }

        public void Listen(string ip, UInt16 port, int backlog = 10)
        {
            m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            m_socket.Blocking = false;
            IPEndPoint ipport = new IPEndPoint(IPAddress.Parse(ip), port);
            m_socket.Bind(ipport);
            m_socket.Listen(backlog);
            m_pSelector.Register(m_socket);
        }

        public void Poll()
        {
            if (m_pSelector.CanRead(m_socket))
            {
                Socket client = m_socket.Accept();
                if (null != client)
                {
                    m_pSelector.Register(client);
                    IMessageChannel pClient = m_pFactory.Create(client);
                    if(null!=m_OnAccept)
                        m_OnAccept(pClient);
                }
            }
        }

        private Socket                  m_socket;
        private Selector                m_pSelector;
        private OnAccept                m_OnAccept;
        private IMessageChannelFactory  m_pFactory;
    }
}
